package com.w2e.user.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

@Data
@Component
@ConfigurationProperties(prefix = "w2e.jwt")
public class JwtUtils {

    // 密钥
    private String secret;
    // Authorization header
    private String header;
    // 过期时间（以秒为单位）
    private long expire;

    // 创建token，传入userId
    public String createToken(Integer userId) {
        Date now = new Date();
        Date expireDate = new Date(now.getTime() + expire * 1000);

        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId.toString())
                .setIssuedAt(now)
                .setExpiration(expireDate)
                .setId(UUID.randomUUID().toString().substring(0,8))
                .signWith(SignatureAlgorithm.HS256, secret);

        return builder.compact();
    }

    // 校验jwt
    public Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    // 判断token是否过期
    public boolean judgeTokenExpiration(Claims claims) {
        return claims.getExpiration().before(new Date());
    }
}
